<?php
/**
 * Created by PhpStorm.
 * User: wangsentao
 * Date: 2018/1/30
 * Time: 下午3:39
 */

namespace app\api\controller\v1;

use app\api\controller\Fun;
use app\api\repository\OrderInfoPayRepository;
use app\common\Model\Order;
use app\common\Utils\BalancePay;
use app\common\Utils\WxPay;
use app\common\Model\AliPayModel;
use app\api\repository\PayLogRespository;
use app\api\repository\OrderRespository;
use think\Db;
use app\common\Utils\AliPay;
use app\api\service\FoundService;

/**
 * @title 订单支付类接口V1
 * @description 接口说明
 *
 * @header name:copyright require:1 default:v1 desc:版本号(全局)
 */
class Pay extends Base
{
    protected $arr;

    static public $validate = [];

    /**
     * @title 支付订单
     * @description
     * @author jikesn
     * @url /api/index/index
     * @method POST
     *
     * @header name:interface require:1 default:Pay desc:接口组(全局)
     *
     * @param name:command type:string require:1 default: other:payOrder desc:
     * @param name:token type:string require:1 default: other: desc:token
     * @param name:uid type:string require:1 default: other: desc:用户id
     * @param name:openid type:string require:0 default: other:选填 desc:微信支付相关使用
     * @param name:shareId type:string require:1 default: other:1 desc:1：支付宝APP；2：微信APP 3：公众号 4：小程序 0:余额支付
     * @param name:orderId type:string require:1 default:0 other:0 desc:订单号
     * @return name:data
     */
    public function payOrder()
    {
        $order_info = $this->arr;

        # 支付逻辑 查询订单号，取出订单信息（金额 支付商品名称）
        $order_res = OrderRespository::instance()->getOrderInfoByOrderId($order_info['orderId']);

        #订单已支付状态提醒
        if ($order_res['or_status'] != 1) {
            return Fun::error('700001');
        }

        $order_res['body'] = '捎货' . $order_res['func_name'];

        if (!$order_res || empty($order_res)) {
            return Fun::error('801013');
        }

        #更新支付类型
        Db::table('sh_order')->where('id',$order_info['orderId'])->setField('pay_type',$order_info['shareId']);

        #生成支付流水
        if ($order_info['shareId'] == 0) {//余额支付
            $pay_channel = 0;
        } else if ($order_info['shareId'] == 1) {
            $pay_channel = 1;
        } else {
            $pay_channel = 2;
        }

        PayLogRespository::instance()->createPayLog(
            $order_res['uid'],
            $order_res['order_num'],
            1,
            2,
            $pay_channel,
            -$order_res['shipping_fee'] // 单位为分 消费为负数
        );

        $order_res['shareId'] = $order_info['shareId'];
        $order_res['totalFee'] = $order_res['shipping_fee'];

        switch ($order_info['shareId']) {
            case '0':
                return BalancePay::pay($order_info['uid'], $order_res);
                break;
            case '1':
                $alipay = new AliPay();
                return Fun::success($alipay->doPay($order_res));
                //$alipay = new AliPayModel();
                //return Fun::success($alipay->doAlPay($order_res));
                break;
            case '2':
                $wxpay = new WxPay($order_info['shareId']);
                return Fun::success($wxpay->appPay($order_res));
                break;
            case '3':
                $wxpay = new WxPay($order_info['shareId']);
                return Fun::success($wxpay->mpPay($order_res));
                break;
            case '4':
                $order_res['openid'] = $order_info['openid'];
                $wxpay = new WxPay($order_info['shareId']);
                return Fun::success($wxpay->miniPay($order_res));
                break;
            default:
                return Fun::error('400001', 'not support payment,place check');
        }
    }

    /**
     * @title 充值
     * @description
     * @author jikesn
     * @url /api/index/index
     * @method POST
     *
     * @header name:interface require:1 default:Pay desc:接口组(全局)
     *
     * @param name:command type:string require:1 default: other:recharge desc:
     * @param name:token type:string require:1 default: other: desc:token
     * @param name:uid type:string require:1 default: other: desc:用户id
     * @param name:appType type:int require:0 default: other:订单来源1公众号2小程序3安卓4ios
     * @param name:totalFee type:int require:0 default: other:总金额 desc:支付总金额
     * @param name:openid type:string require:0 default: other:选填 desc:微信支付相关使用 小程序和公众号使用
     * @param name:shareId type:string require:1 default: other:1 desc:1：支付宝APP；2：微信APP 3：公众号 4：小程序
     *
     * @return name:data
     */
    public function recharge()
    {
        $param = $this->arr;
        $order_info = $this->arr;
        $order_info['body'] = '捎货充值';
        Db::startTrans();

        try {
            //生成主订单
            $order_res = OrderRespository::instance()->createOrder($order_info['uid'], Order::RE, $order_info['appType'], $order_info['shareId']);

            //生成充值详情表
            OrderInfoPayRepository::instance()->createPayOrder(
                $order_res['uid'],
                $order_res['id'],
                $order_res['order_num'],
                $order_res['pay_type'],
                $order_info['totalFee'] * config('convert_unit')
            );

            //生成充值流水表
            PayLogRespository::instance()->createPayLog(
                $order_res['uid'],
                $order_res['order_num'],
                1,
                1,
                $order_info['shareId'] == 1 ? 1 : 2,
                $order_info['totalFee'] * config('convert_unit') // 单位为分
            );

            $order_info['order_num'] = $order_res['order_num'];
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return Fun::error('801007', $e->getMessage());
        };

        switch ($order_info['shareId']) {
            case '1':
                //$alipay = new AliPayModel();
                $alipay = new AliPay();
                return Fun::success($alipay->doPay($order_info));
                break;
            case '2':
                $wxpay = new WxPay($order_info['shareId']);
                return Fun::success($wxpay->appPay($order_info));
                break;
            case '3':
                $wxpay = new WxPay($order_info['shareId']);
                return Fun::success($wxpay->mpPay($order_info));
                break;
            case '4':
                $wxpay = new WxPay($order_info['shareId']);
                return Fun::success($wxpay->miniPay($order_info));
                break;
            default:
                return Fun::error('400001', 'not support payment,place check');
        }
    }

    public function found()
    {
        $param = $this->arr;
        $res = FoundService::instance()->drawBack($param['order_id']);
        pre($res);
    }
}